import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'
import { Request, Response } from 'express'
import { Logger } from '~/src/common/middleware/log/index'

@Catch(HttpException)
export class GlobalHttpFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const req = ctx.getRequest<Request>()
    const response = ctx.getResponse<Response>()
    const status = exception.getStatus();
    // 过滤器日志异常记录


    if (status >= 500) {
      const logRow = `url: ${req.originalUrl}  |method: ${req.method}  | ip: ${req.ip} | body: ${JSON.stringify(req.body)} | query: ${JSON.stringify(req.query)} | params: ${JSON.stringify(req.params)} | status: ${status}  | message: ${exception.toString()}`;
      Logger.error(logRow)
    } else if (status >= 400) {
      const logRow = `url: ${req.originalUrl}  |method: ${req.method}  | ip: ${req.ip} | body: ${JSON.stringify(req.body)} | query: ${JSON.stringify(req.query)} | params: ${JSON.stringify(req.params)} | status: ${status}  | message: ${exception.toString()}`;
      Logger.warn(logRow)
    }

    response.status(status).json({
      data: exception.message,
      time: new Date().getTime(),
      success: false,
      path: req.url,
      status
    })
  }
}